<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/6/5
 * Time: 11:13
 */

namespace app\admin\controller\shop;


use app\admin\BaseController;
use app\admin\model\TradeArea;
use app\admin\model\TradeHall;
use app\lib\exception\FailedException;
use app\Validate\HallAreaValidate;
use app\Validate\IdArrayMustPositive;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\TradeHallValidate;
use think\Request;

class Trade extends BaseController {
    /**
     * 区域管理列表
     * area_name 区域列表里面的 区域名称搜索
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function hallList(Request $request){
        (new PageMustValidate())->goCheck();
         $post = $request->post();
         $where = [];
         $where = addWhere($post,["area_name"=>''],$where,2);//模糊查找区域列表里的数据
         $count = (new TradeArea())->getCount($where);
         $where['page'] = $post['page'];
         $dataList = (new TradeArea())->wechatList($where,"*","id",$post['page_number']);
         foreach ($dataList as $key=>$value){
             $dataList[$key]['is_use'] = (new TradeHall())->getCount([['area_id','eq',$value['id']]]);
             $dataList[$key]['total_number'] = $value['max_line']*$value['max_row'];
         }
         $returnData = [
            'count' =>$count,
            'dataList'=>$dataList
         ];
         return writeJson(200,$returnData);
    }

    /**
     * 添加区域
     * area_name  区域名称  max_line 区域行 max_row 区域的列
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function hallAdd(Request $request){
        (new HallAreaValidate())->goCheck();
        $post = $request->post();
        $new  = [
            'area_name'=>$post['area_name'],
            'max_line' =>$post['max_line'],
            'max_row'  =>$post['max_row'],
        ];
        $res = (new TradeArea())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'添加区域失败']);
        }else{
             return writeJson(200);
        }
    }

    /**
     * 编辑区域
     * area_name  区域名称  max_line 区域行 max_row 区域的列
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function hallEdit(Request $request){
        (new HallAreaValidate())->goCheck();
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $list = (new TradeArea())->findOne([['id','eq',$post['id']]]);
        if($list['max_row']>$post['max_row']||$list['max_line']>$post['max_line']){

            throw new FailedException(['msg'=>'列数不能小于'.$list['max_row'].',行数不能小于'.$list['max_line']]);
        }
        $new  = [
            'id'       =>$post['id'],
            'area_name'=>$post['area_name'],
            'max_line' =>$post['max_line'],
            'max_row'  =>$post['max_row'],
        ];
        $res = (new TradeArea())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'编辑区域失败']);
        }else{
            return writeJson(200);
        }
    }

    /**
     * 清空区域
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function hallClear(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $list = (new TradeArea())->findOne([['id','eq',$post['id']]]);
        if(!$list){ throw new FailedException(['msg'=>'区域不存在']); }

        $res = (new TradeHall())->fieldUpdate("delete_time",time(),"",[['area_id','eq',$post['id']]]);
        if(!$res){
            throw new FailedException(['msg'=>'区域清空失败']);
        }else{
            return writeJson(200,[],'清空成功');
        }
    }

    /**
     * 产品列表
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function productList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where=[];
        $where[]=['a.id','gt',0];
        $where = addWhere($post,['product_name'=>""],$where,2,"b.");//产品名称
        $field = "a.*,b.hot_number,b.visitor_number,b.cover_img,b.product_name,b.publish_time,b.sales_actual_number,c.name,d.price";
        $dataList = (new TradeHall())
            ->alias("a")
            ->join("om_product b","a.product_id = b.id","right")
            ->join("om_shop c","b.uid = c.id","right")
            ->join("om_product_price d","a.product_id = d.product_id and d.type = 1 and d.delete_time is null","right")
            ->field($field)
            ->where($where)
            ->order("a.id desc")
            ->paginate($post['page_number'], false, [
                'page' => $post['page']]);
        $dataList=$dataList->toArray();
        $count = $dataList['total'];
        $dataList = $dataList['data'];
        foreach ($dataList as $key=>$value){
            $dataList[$key]['cover_img'] = imgUrlToAbsolute($value['cover_img']);
        }
        $returnList = [
          'count'=>$count,
          'dataList'=>$dataList
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 上下架 交易大厅商品
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function productPublish(Request $request){
        (new  IdArrayMustPositive())->goCheck();
        $post = $request->post();

        $new = ['is_publish'=>$post['is_publish']];
        $res = (new TradeHall())->where('id','in',$post['id'])->update($new);
        if($res){
            return writeJson(200,[],"操作成功");
        }else{
            throw new FailedException(['msg'=>'操作失败']);
        }
    }

    /**
     * 交易大厅删除商品
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function tradeProductDelete(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $res = (new TradeHall())->fieldUpdate("delete_time",time(),"",["id"=>$post["id"]]);
        if($res){
            return writeJson(200,[],"操作成功");
        }else{
            throw new FailedException(['msg'=>'操作失败']);
        }
    }

    /**
     * 上下架 交易大厅商品
     * @param Request $request
     * @return\think\response\Json
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function productAdd(Request $request){
        (new TradeHallValidate())->goCheck();
        $post = $request->post();
        $area  = (new TradeArea())->findOne([['id','eq',$post['area_id']]]);
        if(!isset($area)){
            throw new FailedException(['msg'=>'区域不存在']);
        }
        if($area['max_line']<$post['line']||$area['max_row']<$post['row']){
            throw new FailedException(['msg'=>'所选行数不能大于'.$post['line'].'所选列数不能大于'.$post['row']]);
        }
        $new = [
            'product_id'=>$post['product_id'],
            'area_id' =>$post['area_id'],
            'line'=>$post['line'],
            'row'=>$post['row'],
            'position_code'=>$post['position_code']
        ];
        $res = (new TradeHall())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'操作失败']);
        }
        return writeJson(200,[],'添加商品成功');
    }

    /**
     * 替换商品
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function replaceProduct(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $count = (new \app\admin\model\Product())->getCount([['id','eq',$post['product_id']]]);
        if($count==0){ throw new FailedException(['msg'=>'商品不存在']);}
        $new = ['id' =>$post['id'], 'product_id'=>$post['product_id']];
        $res = (new TradeHall())->dataUpdate($new);
        if(!$res){ throw new FailedException(['msg'=>'操作失败']); }
        return writeJson(200,[],'替换成功');
    }
}